package com.genia.toolbox.security.annotation.ws_interceptor;

import java.io.OutputStream;

import org.apache.cxf.interceptor.LoggingMessage;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.io.CachedOutputStreamCallback;
import org.apache.cxf.message.Message;
import org.apache.log4j.Logger;

/**
 *
 * Callback used by the ReadOutInterceptor to print the message
 *
 */
public class LoggingCallback implements CachedOutputStreamCallback {

	private static final Logger logger = Logger.getLogger(LoggingCallback.class);
    private final Message message;
    private final OutputStream origStream;
    private int limit = 100 * 1024;

    public void setLimit(int lim) {
        limit = lim;
    }

    public int getLimit() {
        return limit;
    }


    public LoggingCallback(final Message msg, final OutputStream os) {
        this.message = msg;
        this.origStream = os;
    }

    public void onFlush(CachedOutputStream cos) {

    }

    public void onClose(CachedOutputStream cos) {

    	final LoggingMessage buffer
            = new LoggingMessage("Outbound Message\n---------------------------");

        String encoding = (String)message.get(Message.ENCODING);

        if (encoding != null) {
            buffer.getEncoding().append(encoding);
        }

        Object headers = message.get(Message.PROTOCOL_HEADERS);
        if (headers != null) {
            buffer.getHeader().append(headers);
        }

        if (cos.getTempFile() == null) {
            if (cos.size() > limit) {
                buffer.getMessage().append("(message truncated to " + limit + " bytes)\n");
            }
        } else {
            buffer.getMessage().append("Outbound Message (saved to tmp file):\n");
            buffer.getMessage().append("Filename: " + cos.getTempFile().getAbsolutePath() + "\n");
            if (cos.size() > limit) {
                buffer.getMessage().append("(message truncated to " + limit + " bytes)\n");
            }
        }
        try {
            cos.writeCacheTo(buffer.getPayload(), limit);
        } catch (Exception ex) {
           logger.error(ex.getMessage());
        }
        /** Log the message send **/
        logger.debug(buffer.getPayload().toString());
        /**
        try {
            //empty out the cache
        	// Locks the output stream to prevent additional writes,
        	// but maintains a pointer to it so an InputStream can be obtained
            //cos.lockOutputStream();
            cos.resetOut(null, false);
        } catch (Exception ex) {
        	logger.error(ex.getMessage());
        }
        **/
        message.setContent(OutputStream.class,
                           origStream);
    }
}
